package com.qingcloud.common.auth.autologin;

import com.qingcloud.common.auth.service.impl.UserDetailServiceFactory;
import com.qingcloud.common.auth.token.AutoLoginAuthenticationToken;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;


@Setter
@Getter
public class AutoLoginAuthenticationProvider implements AuthenticationProvider {

    private UserDetailServiceFactory userDetailsServiceFactory;

    @Override
    public Authentication authenticate(Authentication authentication) {
        AutoLoginAuthenticationToken authenticationToken = (AutoLoginAuthenticationToken) authentication;
        String userId = (String) authenticationToken.getPrincipal();
        UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByOpenId(userId);
        if (user == null) {
            throw new InternalAuthenticationServiceException("自动登录ID错误");
        }
        AutoLoginAuthenticationToken authenticationResult = new AutoLoginAuthenticationToken(user, "", user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AutoLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
